/**
 * Copyright (C), 2020-2021 by colley.ma
 * File Name: SwakTaskRegistrar.java
 * Encoding: UTF-8
 * Date: 2021年4月21日 下午2:40:53
 * History:
 */
package com.swak.frame.job;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.swak.frame.aware.MonitorAware;
import com.swak.frame.common.SpringBeanFactory;
import com.swak.frame.job.annotation.SwakJob;
import com.swak.frame.system.SystemConfigurable;

public class SwakTaskJobRegister implements MonitorAware {

    private SystemConfigurable systemConfig;

    public void setSystemConfig(SystemConfigurable systemConfig) {
        this.systemConfig = systemConfig;
    }

    protected void doRegistration(RefreshConfigurable refreshConfigurable) {
        Class<?> extensionClz = refreshConfigurable.getClass();
        SwakJob swakJob = extensionClz.getDeclaredAnnotation(SwakJob.class);
        if (StringUtils.isNotEmpty(swakJob.cron()) || swakJob.fixedRate() > 0) {
            refreshConfigurable.setRefreshRate(
                new RefreshRate(swakJob.cron(), swakJob.fixedRate(), swakJob.unit()));
        }
        if (systemConfig.isRunJob()) {
            refreshConfigurable.startJob();
        }
    }

    @Override
    public void startup() {
        Map<String, Object> swakJobBean =
            SpringBeanFactory.getContext().getBeansWithAnnotation(SwakJob.class);
        if (swakJobBean != null) {
            swakJobBean.values().forEach(jobBean -> doRegistration((RefreshConfigurable) jobBean));
        }
    }

    @Override
    public boolean enabled() {
        // TODO Auto-generated method stub
        return MonitorAware.super.enabled();
    }


}
